import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Calendar;

/**
 * 
 */

/**
 * @author lucas
 *
 */
public class ComputeUDP extends Thread {

	private Environment _env; 
	
	public ComputeUDP(){
		_env = new Environment(); 
	}
	
	public ComputeUDP(Environment env){
		_env = env;
	}
	
	private void runClientUDP() throws IOException{
		int size = _env.get_bufferSize(); 
		int sizeData = 10*Environment.KB64;
		int send = sizeData/size;
		int port = _env.get_port();
		Calendar begin, end;
		
		byte[] sendData = new byte[size];
		byte[] receiveData = new byte[size];
		for (int i=0; i< size; i++){
			sendData[i] = (byte) 42;
		}

		DatagramSocket clientSocket = new DatagramSocket();
		InetAddress IPAddress = InetAddress.getByName(_env.get_loopbackAddr());
		begin = Calendar.getInstance();
		for (int i=0; i< send; i++){
			DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
			clientSocket.send(sendPacket);
			DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
			clientSocket.receive(receivePacket);
		}
		end = Calendar.getInstance();
		clientSocket.close();
		float time = end.getTimeInMillis()-begin.getTimeInMillis();
		if (size == Environment.B){
			float latency = (20*Environment.KB64)/time;
			System.out.println("Latency : " + latency); 	
			System.err.println(latency+";");
		}
		float throughtput = (float) (((float)20*(float)Environment.KB64)/(float)Environment.MB);
		throughtput = (float) (throughtput/(time/(float)1000.0)); 
		System.out.println("Total time in millisecond : " + time); 
		System.out.println("Throughtput : " + throughtput + " MB/s"); 
		System.err.println(";"+throughtput+";");
	}

	@Override
	public void run() {
		try {
			runClientUDP();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
}
